<!-- 专注力测评因子编辑弹窗 -->
<template>
  <el-dialog
    :destroy-on-close="true"
    :lock-scroll="false"
    :title="isUpdate?'修改专注力测评因子':'添加专注力测评因子'"
    :visible="visible"
    width="55%"
    top="3%"
    @update:visible="updateVisible">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px">

      <el-form-item
        label="因子:"
        prop="title">
        <el-input
          v-model="form.title"
          :maxlength="20"
          clearable
          placeholder="请输入维度"/>
      </el-form-item>

      <el-form-item
        label="展示权重:"
        prop="weight">
        <el-input
          v-model="form.weight"
          :maxlength="20"
          clearable
          placeholder="请输入展示权重，数值越大展示位置越靠前"/>
      </el-form-item>

      <el-form-item
        label="描述:"
        prop="desc">
        <tinymce-editor v-model="form.desc" :init="initEditor"></tinymce-editor>
      </el-form-item>

      <el-form-item
        label="小提示:"
        prop="tips">
        <el-input
          v-model="form.tips"
          :maxlength="20"
          clearable
          placeholder="请输入小提示"/>
      </el-form-item>

      <el-form-item
        v-for="(rule, index) in form.format_calc_rules"
        :key="index"
        :label="'计算规则' + parseInt(index + 1) + '：'"
        :prop="'format_calc_rules.' + index + '.result'"
        :rules="{
          required: true, message: '输出结果不能为空', trigger: 'blur'
        }">
        <el-row>
          <el-col :span="7">
            <el-form-item
              :prop="'format_calc_rules.' + index + '.result'"
              :rules="{
                required: true, message: '输出结果不能为空', trigger: 'blur'
              }">
              <el-input
                v-model="rule.result"
                :maxlength="20"
                clearable
                placeholder="请输入结果"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
              :prop="'format_calc_rules.' + index + '.min'"
              :rules="{
                required: true, message: '最小分值不能为空', trigger: 'blur'
              }">
              <el-input pattern="[0-9]*" @input="handleInput(index, $event)"   placeholder="最小分数" v-model="rule.min" style="margin-left: 5px">
                <template slot="prepend">最小</template>
                <template slot="append">分</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
              :prop="'format_calc_rules.' + index + '.max'"
              :rules="{
                required: true, message: '最大分值不能为空', trigger: 'blur'
              }">
              <el-input pattern="[0-9]*" @input="handleInput(index, $event)"   placeholder="最大分数" v-model="rule.max" style="margin-left: 10px">
                <template slot="prepend">最大</template>
                <template slot="append">分</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button style="margin-left: 15px" type="danger" size="mini" @click.prevent="removeCalcRule(rule)">删除</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <tinymce-editor v-model="rule.desc" :init="initEditor"></tinymce-editor>
          </el-col>
        </el-row>
        <el-button v-if="form.format_calc_rules.length == 0 || index+1 == form.format_calc_rules.length" type="primary" @click.prevent="addCalcRule" size="mini">添加计算规则</el-button>
      </el-form-item>

      <el-form-item
        label="备注:">
        <el-input
          type="textarea"
          rows="5"
          v-model="form.remark"
          clearable
          placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button
        :loading="loading"
        type="primary"
        @click="save">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import TinymceEditor from '@/components/TinymceEditor'
export default {
  name: 'AttentionFactorEdit',
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  components: {TinymceEditor},
  data() {
    return {
      // 表单数据
      form: Object.assign({status: 1}, this.data),
      // 表单验证规则
      rules: {
        title: [
          {required: true, message: '请输入维度', trigger: 'blur'}
        ],
        desc: [
          {required: true, message: '请输入描述', trigger: 'blur'}
        ],
        tips: [
          {required: true, message: '请输入小提示', trigger: 'blur'}
        ],
        calc_rule: [
          {required: true, message: '请输入计算规则', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '请输入备注', trigger: 'blur'}
        ],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false
    };
  },
  computed: {
    initEditor() {
      return {
        height: 400,
        file_picker_callback: this.file_picker_callback,
        skin_url: this.$store.state.theme.theme === 'dark' ? '/tinymce/skins/ui/oxide-dark' : '/tinymce/skins/ui/oxide',
        content_css: this.$store.state.theme.theme === 'dark' ? '/tinymce/skins/content/dark/content.css' : '/tinymce/skins/content/default/content.css',
        images_upload_handler: (blobInfo, success, error) => {
          let file = blobInfo.blob();
          // 使用axios上传
          const formData = new FormData();
          formData.append('file', file, file.name);
          this.$http.post('/upload/uploadImage', formData).then(res => {
            if (res.data.code == 0) {
              success(res.data.data);
            } else {
              error(res.data.msg);
            }
          }).catch(e => {
            console.error(e);
            error(e.message);
          });
        }
      };
    }
  },
  watch: {
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data);
        this.isUpdate = true;
      } else {
        this.form = {};
        this.isUpdate = false;
      }
    }
  },
  methods: {
    /* 保存编辑 */
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.form.calc_rule = JSON.stringify(this.form.format_calc_rules)
          this.$http.post('/attentionfactor/edit', this.form).then(res => {
            this.loading = false;
            if (res.data.code === 0) {
              this.$message.success(res.data.msg);
              if (!this.isUpdate) {
                this.form = {};
              }
              this.updateVisible(false);
              this.$emit('done');
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            this.loading = false;
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    handleInput(index, value) {
      // 去除输入值中的非数字字符
      this.form.format_calc_rules[index].value = value.replace(/[^\d]/g, '');
    },
    removeCalcRule(item) {
      var index = this.form.format_calc_rules.indexOf(item)
      if (index !== -1) {
        this.form.format_calc_rules.splice(index, 1)
      }
    },
    addCalcRule() {
      this.form.format_calc_rules.push({
        label: '',
        value: ''
      });
    }
  }
}
</script>

<style scoped>
</style>
